/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AdministrrGruposJInternalFrame.java
 *
 * Created on Jun 21, 2013, 12:24:03 PM
 */
package pe.edu.unmsm.cinfo.siga.ui.ventanas;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.Collections;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.jdesktop.application.Action;
import org.jdesktop.observablecollections.ObservableCollections;
import pe.edu.unmsm.cinfo.siga.datos.Horario;
import pe.edu.unmsm.cinfo.siga.datos.Modulo;
import pe.edu.unmsm.cinfo.siga.datos.ModuloGrupo;
import pe.edu.unmsm.cinfo.siga.ui.Main;
/**
 *
 * @author Carito
 */
public class AdministrarGruposInternalFrame extends javax.swing.JInternalFrame {

    /** Creates new form AdministrrGruposJInternalFrame */
    public AdministrarGruposInternalFrame() {
        initComponents();
        establecerOyentes();
        botonCalendario.setEnabled(false);
    }
    private void establecerOyentes(){
        tabla.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                getChangeSupport().firePropertyChange("seleccionado", !isSeleccionado(), isSeleccionado());
            }
        });
        comboModulo.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                getChangeSupport().firePropertyChange("comboModuloSeleccionado", 
                        !isComboModuloSeleccionado(), 
                        isComboModuloSeleccionado());
            }
        });
    }

  
    public boolean isSeleccionado() {
        return tabla.getSelectedRow() != -1;
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(pe.edu.unmsm.cinfo.siga.ui.Main.class).getContext().getResourceMap(AdministrarGruposInternalFrame.class);
        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory(resourceMap.getString("entityManager.persistenceUnit")).createEntityManager(); // NOI18N
        consultaGrupo = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery(resourceMap.getString("consultaGrupo.query")); // NOI18N
        listaModulos = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : consultaGrupo.getResultList();
        grupoSeleccionado = null;
        moduloSeleccionado = null;
        listaGrupos = null;
        atras = new javax.swing.JButton();
        adelante = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        actualizar = new javax.swing.JButton();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        scrollPanel = new javax.swing.JScrollPane();
        tabla = new javax.swing.JTable();
        comboModulo = new javax.swing.JComboBox();
        botonNuevo = new javax.swing.JButton();
        botonModificar = new javax.swing.JButton();
        botonCalendario = new javax.swing.JButton();
        ultimo = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();

        setClosable(true);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(pe.edu.unmsm.cinfo.siga.ui.Main.class).getContext().getActionMap(AdministrarGruposInternalFrame.class, this);
        atras.setAction(actionMap.get("anteriorAction")); // NOI18N
        atras.setIcon(resourceMap.getIcon("atras.icon")); // NOI18N
        atras.setText(resourceMap.getString("atras.text")); // NOI18N
        atras.setName("atras"); // NOI18N

        adelante.setAction(actionMap.get("siguienteAction")); // NOI18N
        adelante.setIcon(resourceMap.getIcon("adelante.icon")); // NOI18N
        adelante.setText(resourceMap.getString("adelante.text")); // NOI18N
        adelante.setName("adelante"); // NOI18N

        jLabel1.setText("Modulo:"); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        actualizar.setAction(actionMap.get("actualizarAction")); // NOI18N
        actualizar.setIcon(resourceMap.getIcon("actualizar.icon")); // NOI18N
        actualizar.setText(resourceMap.getString("actualizar.text")); // NOI18N
        actualizar.setName("actualizar"); // NOI18N

        jTabbedPane1.setName("jTabbedPane1"); // NOI18N

        scrollPanel.setName("scrollPanel"); // NOI18N

        tabla.setAutoCreateRowSorter(true);
        tabla.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        tabla.setName("tabla"); // NOI18N
        tabla.getTableHeader().setReorderingAllowed(false);

        org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${listaGrupos}");
        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, tabla);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${modgCod}"));
        columnBinding.setColumnName("Modg Cod");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${doceCod.doceNom}"));
        columnBinding.setColumnName("Doce Cod.doce Nom");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${modgNins}"));
        columnBinding.setColumnName("Modg Nins");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${modgVac}"));
        columnBinding.setColumnName("Modg Vac");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${aulCod.aulCod}"));
        columnBinding.setColumnName("Aul Cod.aul Cod");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${modgFini}"));
        columnBinding.setColumnName("Inicio");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${modgHor}"));
        columnBinding.setColumnName("Modg Hor");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        jTableBinding.setSourceNullValue(Collections.EMPTY_LIST);
        jTableBinding.setSourceUnreadableValue(Collections.EMPTY_LIST);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${grupoSeleccionado}"), tabla, org.jdesktop.beansbinding.BeanProperty.create("selectedElement"));
        bindingGroup.addBinding(binding);

        scrollPanel.setViewportView(tabla);
        tabla.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tabla.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("tabla.columnModel.title0")); // NOI18N
        tabla.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("tabla.columnModel.title1")); // NOI18N
        tabla.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("tabla.columnModel.title2")); // NOI18N
        tabla.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("tabla.columnModel.title3")); // NOI18N
        tabla.getColumnModel().getColumn(4).setHeaderValue(resourceMap.getString("tabla.columnModel.title4")); // NOI18N
        tabla.getColumnModel().getColumn(6).setHeaderValue(resourceMap.getString("tabla.columnModel.title6")); // NOI18N

        jTabbedPane1.addTab(resourceMap.getString("scrollPanel.TabConstraints.tabTitle"), scrollPanel); // NOI18N

        comboModulo.setName("comboModulo"); // NOI18N
        comboModulo.setRenderer(new pe.edu.unmsm.cinfo.siga.ui.utils.ModuloListCellRenderer());

        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, listaModulos, comboModulo);
        bindingGroup.addBinding(jComboBoxBinding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${moduloSeleccionado}"), comboModulo, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        botonNuevo.setAction(actionMap.get("crearGrupo")); // NOI18N
        botonNuevo.setIcon(resourceMap.getIcon("botonNuevo.icon")); // NOI18N
        botonNuevo.setText(resourceMap.getString("botonNuevo.text")); // NOI18N
        botonNuevo.setName("botonNuevo"); // NOI18N

        botonModificar.setAction(actionMap.get("modificarGrupo")); // NOI18N
        botonModificar.setIcon(resourceMap.getIcon("botonModificar.icon")); // NOI18N
        botonModificar.setName("botonModificar"); // NOI18N

        botonCalendario.setText("Calendario"); // NOI18N
        botonCalendario.setEnabled(false);
        botonCalendario.setName("botonCalendario"); // NOI18N

        ultimo.setAction(actionMap.get("ultimoAction")); // NOI18N
        ultimo.setIcon(resourceMap.getIcon("ultimo.icon")); // NOI18N
        ultimo.setText(resourceMap.getString("ultimo.text")); // NOI18N
        ultimo.setName("ultimo"); // NOI18N

        jButton1.setAction(actionMap.get("primeroAction")); // NOI18N
        jButton1.setIcon(resourceMap.getIcon("jButton1.icon")); // NOI18N
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 691, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(28, 28, 28)
                        .addComponent(comboModulo, 0, 269, Short.MAX_VALUE)
                        .addGap(43, 43, 43)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(botonNuevo)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(botonModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(botonCalendario))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(atras, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(adelante, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(ultimo, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(2, 2, 2)
                                .addComponent(actualizar, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(33, 33, 33)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(botonCalendario)
                            .addComponent(botonNuevo)
                            .addComponent(botonModificar)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(comboModulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(actualizar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE)
                    .addComponent(ultimo, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE)
                    .addComponent(adelante, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE)
                    .addComponent(atras, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    @Action(enabledProperty = "comboModuloSeleccionado")
    public void crearGrupo() {        
        JFrame mainFrame = Main.getApplication().getMainFrame();
        CrearNuevoGrupoDialog ngd = new CrearNuevoGrupoDialog(mainFrame, true);
        ngd.setLocationRelativeTo(mainFrame);
        ModuloGrupo grupoNuevo = new ModuloGrupo();
        grupoNuevo.setModCod(getModuloSeleccionado());
        ngd.setGrupoEditado(grupoNuevo);
        ngd.setVisible(true);
        
        if(ngd.isEntityConfirmed()){
             try {
                 entityManager.getTransaction().begin();
                 asignarDatosAGrupo(ngd.getGrupoEditado());
                 entityManager.persist(ngd.getGrupoEditado());
                 entityManager.getTransaction().commit();
                 listaGrupos.add(ngd.getGrupoEditado());
             } catch (Exception e) {
                 entityManager.getTransaction().rollback();
                 JOptionPane.showMessageDialog(this, e.getMessage());
             }
        }
        tabla.clearSelection();
        mostrarFila(tabla.getRowCount()-1);
    }
    
    private void mostrarFila(int fila){
        if(fila < 0 || fila > tabla.getRowCount()-1) return;
        tabla.setRowSelectionInterval(fila, fila);
        tabla.scrollRectToVisible(tabla.getCellRect(fila, 0, true));
    }
    
    private void asignarDatosAGrupo(ModuloGrupo grupoEditado) {
        for(Horario horario : grupoEditado.getHorarioList()){
            horario.getHorarioPK().setModgCod(grupoEditado.getModgCod());
        }
    }
    
        @Action(enabledProperty = "seleccionado")
    public void modificarGrupo() {
        int indice = tabla.convertRowIndexToModel(tabla.getSelectedRow());
        
        JFrame mainFrame = Main.getApplication().getMainFrame();
        CrearNuevoGrupoDialog ngd = new CrearNuevoGrupoDialog(mainFrame, true);
        ngd.setLocationRelativeTo(mainFrame);
        ngd.setGrupoEditado(getGrupoSeleccionado());
        
        ngd.setVisible(true);
        if(ngd.isEntityConfirmed()){
            try{
                entityManager.getTransaction().begin();
                asignarDatosAGrupo(ngd.getGrupoEditado());
                entityManager.merge(ngd.getGrupoEditado());
                entityManager.getTransaction().commit();
                listaGrupos.set(indice, ngd.getGrupoEditado());
            } catch (Exception e) {
                entityManager.getTransaction().rollback();
                JOptionPane.showMessageDialog(this, e.getMessage());
            }
        }else{
            entityManager.refresh(getGrupoSeleccionado());
        }
        
    }
    
    public boolean isComboModuloSeleccionado() {
        return comboModulo.getSelectedIndex() != -1;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton actualizar;
    private javax.swing.JButton adelante;
    private javax.swing.JButton atras;
    private javax.swing.JButton botonCalendario;
    private javax.swing.JButton botonModificar;
    private javax.swing.JButton botonNuevo;
    private javax.swing.JComboBox comboModulo;
    private javax.persistence.Query consultaGrupo;
    private javax.persistence.EntityManager entityManager;
    private pe.edu.unmsm.cinfo.siga.datos.ModuloGrupo grupoSeleccionado;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private java.util.List<ModuloGrupo> listaGrupos;
    private java.util.List<Modulo> listaModulos;
    private pe.edu.unmsm.cinfo.siga.datos.Modulo moduloSeleccionado;
    private javax.swing.JScrollPane scrollPanel;
    private javax.swing.JTable tabla;
    private javax.swing.JButton ultimo;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    private PropertyChangeSupport changeSupport;

    public Modulo getModuloSeleccionado() {
        return moduloSeleccionado;
    }

    public void setModuloSeleccionado(Modulo moduloSeleccionado) {
        Modulo old = getModuloSeleccionado();
        this.moduloSeleccionado = moduloSeleccionado;
        getChangeSupport().firePropertyChange("moduloSeleccionado", old, getModuloSeleccionado());
        setListaGrupos(moduloSeleccionado.getModuloGrupoList());
    }

    public List<ModuloGrupo> getListaGrupos() {
        return listaGrupos;
    }

    public void setListaGrupos(List<ModuloGrupo> listaGrupos) {
        List<ModuloGrupo> old = getListaGrupos();
        this.listaGrupos = ObservableCollections.observableList(listaGrupos);
        getChangeSupport().firePropertyChange("listaGrupos", old, getListaGrupos());
    }
    
    public ModuloGrupo getGrupoSeleccionado() {
        return grupoSeleccionado;
    }

    public void setGrupoSeleccionado(ModuloGrupo grupoSeleccionado) {
        ModuloGrupo old = this.grupoSeleccionado;
        this.grupoSeleccionado = grupoSeleccionado;
        getChangeSupport().firePropertyChange("grupoSeleccionado", old, grupoSeleccionado);
    }
    
    public PropertyChangeSupport getChangeSupport() {
        if(changeSupport == null) changeSupport = new PropertyChangeSupport(this);
        return changeSupport;
    }
    
    @Override
    public void addPropertyChangeListener(PropertyChangeListener l){
        getChangeSupport().addPropertyChangeListener(l);
    }
    
    @Override
    public void removePropertyChangeListener(PropertyChangeListener l){
        getChangeSupport().removePropertyChangeListener(l);
    }

    @Action
    public void primeroAction() {
        mostrarFila(0);
    }

    @Action
    public void anteriorAction() {
        int previo = tabla.getSelectedRow() - 1;
        if (previo < 0) previo = 0;
        mostrarFila(previo);
    }

    @Action
    public void siguienteAction() {
        int siguiente = tabla.getSelectedRow() + 1;
        if(siguiente > tabla.getRowCount()-1) siguiente = tabla.getRowCount()-1;
        mostrarFila(siguiente);
    }

    @Action
    public void ultimoAction() {
        mostrarFila(tabla.getRowCount()-1);
    }

    @Action
    public void actualizarAction() {
        return;
    }
}
